package com.demo.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 使用httpcomponents发送请求<br></>
 * post，get请求，不同的contentType
 * Created by liangqingqing on 2018/5/15.
 */
@Slf4j
public class HttpUtil {

    //localhost
    private static String HOST = "https://www.baidu.com";
    private static String PATH = "/";


    /**
     * 测试post请求
     * @throws IOException
     */
    @Test
    public void test_post() throws IOException {

        Map<String, String> params = new HashMap<>();
        params.put("wd", "中国");
        log.info("请求时的参数：{}" , JSONObject.toJSONString(params));
        String body = post(HOST +PATH,params);
        log.info("返回结果：{}",body);
    }

    /**
     * 测试get请求
     * @throws IOException
     */
    @Test
    public void test_get() throws IOException {
        String param = "?wd=China";
        log.info("请求时的地址：{}" , param);
        String requestURL = HOST +PATH + param;
        String body = get(requestURL);
        log.info("返回结果：{}",body);
    }


    /**
     * 发送post请求
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        /**
         * HTTP请求最基本的客户端，不包含细节
         */
        HttpClient client = null;
        CloseableHttpClient closeableHttpClient  = HttpClientBuilder.create()
                //.


                .build();

        HttpPost post = getJsonHttpPost(url, params);

        String body = invoke(closeableHttpClient, post);
        //closeableHttpClient.getConnectionManager().shutdown();

        return body;
    }

    /**
     * 发送get请求
     * @param url
     * @return
     */
    public static String get(String url) {
        CloseableHttpClient httpclient  = HttpClientBuilder.create()
                //.
                .build();
        String body = null;

        HttpGet get = new HttpGet(url);
        body = invoke(httpclient, get);

        //httpclient.getConnectionManager().shutdown();

        return body;
    }

    /**
     * 实际发送请求
     * @param httpclient
     * @param httpUriRequest
     * @return
     */
    private static String invoke(HttpClient httpclient, HttpUriRequest httpUriRequest) {

        HttpResponse response =  null;
        try {
            response = httpclient.execute(httpUriRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String body = null;
        //200返回消息内容
        if(response != null &&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = response.getEntity();

            try {
                /**
                 * 将返回的content以string形式返回
                 */
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return body;

    }


    private static HttpPost postForm(String url, Map<String, String> params) {

        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        // 需要传一个token
        //httpost.setHeader("token", "c7a4e021-6527-11e6-96be-fcaa14c3021a1");
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }

        //HttpEntity entity = new
        //httpost.setEntity();
        return httpost;
    }

    private static HttpPost getJsonHttpPost(String url, Map<String, String> params) {

        /**
         * HTTP POST method. 就是http的post请求方法。
         */
        HttpPost httPost = new HttpPost(url);
        httPost.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()));

        // 构造请求数据
        /**
         * An entity that can be sent or received with an HTTP message
         * 代表发送或者接收的http消息
         */
        HttpEntity myEntity = null;
        try {
            myEntity = new StringEntity(JSONObject.toJSONString(params));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httPost.setEntity(myEntity);


        return httPost;
    }


}
